package ch.bfh.mobicomp.ui.output;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import ch.bfh.mobicomp.AlarmManager;
import ch.bfh.mobicomp.R;

/**
 * 
 * @author Dominik
 * 
 */

public class AudioBell extends BroadcastReceiver {
	private static Thread thread;
	//TODO: Broadcasts must be updated in the manifest!

	@Override
	public void onReceive(final Context context, Intent intent) {
		Log.d("alarm", "startcommand");
		if (intent.getAction() != null) {
			Log.d("alarm", "not null");
			// SERVICE ON
			if (intent.getAction().equals(AlarmManager.GLOBAL_ALARM_ON)) {
				Log.d("alarm", "on");
				if (thread == null || !thread.isAlive()) {
					thread = new Thread(new Runnable() {
						@Override
						public void run() {
							while (!Thread.interrupted()) {
								try {
									MediaPlayer mp = MediaPlayer.create(
											context, R.raw.alarm);
									mp.start();
									while (mp.isPlaying()) {
										Thread.sleep(200);
									}
								} catch (InterruptedException e) {
									Thread.currentThread().interrupt();
								}
							}
						}
					});
					thread.start();
				}
			}
			// SERVICE OFF
			if (intent.getAction().equals(AlarmManager.GLOBAL_ALARM_OFF)) {
				Log.d("alarm", "OFF");
				if (thread != null)
					thread.interrupt();
			}
		}
	}
}
